<?php

namespace app\controller\api;

use app\model\CheckRecord as CheckRecordModel;
use app\model\Railway as RailwayModel;
use app\model\RailwayStation as RailwayStationModel;
use app\util\ReturnCode;
use think\exception\ValidateException;
use app\model\User as UserModel;
use app\model\CheckType as CheckTypeModel;
use app\model\CheckItem as CheckItemModel;
class Railway extends Base
{

    public function getAll()
    {
        $lists = RailwayModel::field('id,name')
            ->select()
            ->toArray();
        return $this->buildSuccess($lists);
    }

    public function recordInfo()
    {
        $id = $this->request->get('id', 0);
        $where = [];
        $where[] = ['id', '=', $id];
        $data = CheckRecordModel::where($where)
            ->with(['railway', 'start', 'end'])
            ->append(['user_name', 'progress_text', 'type_name', 'direction_text'])
            ->find()
            ->toArray();
        $start_name = $data['start']['name'] ?? '';
        $end_name = $data['end']['name'] ?? '';
        $data['station_name'] = $start_name . '-' . $end_name . '段';
        $data['image_urls'] = $data['image_url'] ? [$data['image_url']] : [];
        $data['station_time'] = $data['station_time'] ? date('Y-m-d h:i:s', $data['station_time']) : '';
        $data['boarding_time'] = $data['boarding_time'] ? date('Y-m-d h:i:s', $data['boarding_time']) : '';
        $data['departure_time'] = $data['departure_time'] ? date('Y-m-d h:i:s', $data['departure_time']) : '';
        $data['arrival_time'] = $data['arrival_time'] ? date('Y-m-d h:i:s', $data['arrival_time']) : '';
        $data['complete_time'] = $data['complete_time'] ? date('Y-m-d h:i:s', $data['complete_time']) : '';
        return $this->buildSuccess($data);
    }
    public function record()
    {
        $rid = $this->request->get('rid', 0);
        $userInfo = $this->getUserInfo();
        $where = [];
        if (!$userInfo['sys']) {
            $where[] = ['user_id', '=', $userInfo['id']];
        }
        if ($rid) {
            $where[] = ['rid', '=', $rid];
        }
        $lists = CheckRecordModel::where($where)
            ->with(['railway', 'start', 'end'])
            ->append(['user_name', 'progress_text', 'type_name', 'direction_text'])
            ->select()
            ->toArray();
        return $this->buildSuccess($lists);
    }
    public function lists()
    {
        $status = $this->request->get('status', 0);
        $lists = RailwayModel::field('id,name')
            ->select()
            ->each(function ($item) {
                // 查RailwayStation中是否存在封锁中
                $where = [
                    ['railway_id', '=', $item['id']],
                    ['status', '>', 1],
                ];
                $lock = RailwayStationModel::where($where)->find();
                $item['status'] = $lock ? 2 : 1;
            })->toArray();
        
        // 如果请求了特定状态，则过滤结果
        if ($status) {
            $lists = array_filter($lists, function($item) use ($status) {
                return $item['status'] == $status;
            });
            $lists = array_values($lists); // 重置数组键
        }
        
        return $this->buildSuccess($lists);
    }

    public function detail()
    {
        $id = $this->request->get('id'); 

        // 使用索引查询
        $where = ['id' => $id];
        $data = RailwayModel::where($where)
            ->with(['station' => function ($query) {
                $query->field('id,railway_id,name,status,sort');
            }])
            ->field('id,name')
            ->find();

        if (!$data) {
            return $this->buildFailed(ReturnCode::INVALID, '未找到相关数据');
        }

        $data = $data->toArray();

        // 获取封锁记录
        $checkRecords = CheckRecordModel::where([
            ['railway_id', '=', $id],
            ['delete_time', '=', null],
            ['status', 'in', [0, 1, 2]]
        ])->select()->toArray();

        // 为每个封锁区间分配颜色
        $colorIndex = 1;
        foreach ($checkRecords as $record) {
            // 获取区间内的所有站点
            $blockedStations = RailwayStationModel::where([
                ['railway_id', '=', $id],
                ['id', 'in', $record['range_ids']]
            ])->select()->toArray();

            // 标记区间内所有站点的颜色
            foreach ($blockedStations as $blockedStation) {
                foreach ($data['station'] as &$station) {
                    if ($station['id'] == $blockedStation['id']) {
                        $station['block_group'] = $colorIndex;
                        $station['check_ids'] = $record['id'];
                        break;
                    }
                }
            }
            $colorIndex++;
        }

        // 批量获取记录数据
        $stationIds = array_column($data['station'], 'id');

        // 一次性查询所有相关记录
        $allRecords = CheckItemModel::where([
            ['railway_id', '=', $id],
            ['start_id', 'in', $stationIds]
        ])
            ->select()
            ->toArray();

        // 按站点ID组织记录
        $recordsByStation = [];
        foreach ($allRecords as $record) {
            $stationId = $record['start_id'];
            if (!isset($recordsByStation[$stationId])) {
                $recordsByStation[$stationId] = [];
            }
            $recordsByStation[$stationId][] = $record;
        }

        $btnArr = [
            1 => '检查',
            2 => '开车',
            3 => '到达',
        ];

        foreach ($data['station'] as &$station) {
            $station['check_btn'] = 1;
            $station['progress'] = 0;
            $station['isExpanded'] = false;
            $stationId = $station['id'];

            // 如果站点状态非正常(status>1),查询最新的未完成记录
            $station['check_status'] = 0;
            if ($station['status'] > 1) {
                $latestRecord = CheckRecordModel::where([
                    ['railway_id', '=', $id],
                    ['range_ids', 'like', '%' . $stationId . '%'],  // 修改为使用range_ids
                    ['status', 'in', [0, 1, 2]],
                    ['delete_time', '=', null]
                ])
                    ->order('id', 'desc')
                    ->find();
                
                if ($latestRecord) {
                    $station['check_record_id'] = $latestRecord['id'];
                    $station['check_status'] = $latestRecord['status'];
                }
            }

            // 使用预先查询的记录
            $stationRecords = $recordsByStation[$stationId] ?? [];

            // 查找添乘记录
            $latestRecord = null;
            foreach ($stationRecords as $record) {
                if ($record['type'] == 1) {
                    if ($record['boarding_time'] > 0 && $record['departure_time'] == 0) {
                        $station['check_btn'] = 2;
                    }
                    if ($record['boarding_time'] > 0 && $record['departure_time'] > 0 && $record['arrival_time'] == 0) {
                        $station['check_btn'] = 3;
                    }
                }

                // 获取最新进度
                if (!isset($latestRecord) || $record['id'] > $latestRecord['id']) {
                    $latestRecord = $record;
                    // 根据检查项目状态设置进度
                    if ($record['status'] == 1) {
                        $station['progress'] = 1;
                    } elseif ($record['status'] == 2) {
                        $station['progress'] = 2;
                    } else {
                        $station['progress'] = 0;
                    }
                }
            }

            $station['btn_text'] = $btnArr[$station['check_btn']] ?? '检查';
        }

        return $this->buildSuccess($data);
    }
 
}
